//
//  MHCircleHomeViewController.m
//  MiaoCircle
//
//  Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHCircleHomeViewController.h"
#import "MHCircleHomeViewModel.h"
#import "MHHomeCircleItemCollectionViewCell.h"
#import "MHCreateCircleCollectionViewCell.h"
#import "WZLBadgeImport.h"
#import "MHIMMessageTransferHelper.h"
#import "MHDebugTouchView.h"
#import "JKRSearchBar.h"
#import "JKRSearchController.h"
#import "MHSearchCircleResultViewController.h"
#import "UIScrollView+MHRefresh.h"
#import "MHCircleUpdateModel.h"

#define kSafeAreaNavHeight (([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125,2436), [[UIScreen mainScreen] currentMode].size) : NO) ? 88 : 64)

#define kRightItemOffset CGPointMake(-10, 10)

@interface MHCircleHomeViewController ()<JKRSearchControllerhResultsUpdating, JKRSearchControllerDelegate>
@property (nonatomic, readwrite, strong) MHCircleHomeViewModel *viewModel;
@property(nonatomic, strong) UIButton *customButton;
@property (nonatomic, strong) JKRSearchController *searchController;

@end

@implementation MHCircleHomeViewController
@dynamic viewModel;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView mh_registerNibCell:MHHomeCircleItemCollectionViewCell.class];
    [self _setupNavigationItem];
//    [[IMAPlatform sharedInstance].conversationMgr asyncConversationList];
    
//    IMAConversationManager *mgr = [IMAPlatform sharedInstance].conversationMgr;
//    _conversationList = [mgr conversationList];
    
//    __weak ConversationListViewController *ws = self;
//    __weak __typeof(self)weakSelf = self;
//    mgr.conversationChangedCompletion = ^(IMAConversationChangedNotifyItem *item) {
//        if (item.type == EIMAConversation_SyncLocalConversation) {
//            [weakSelf reloadData];
//        }
//    };
    
    self.view.backgroundColor = [UIColor whiteColor];
    @weakify(self);
    [[MHNotificationCenter rac_addObserverForName:MHReloadFirstPageDataNotification object:nil] subscribeNext:^(NSNotification *note) {
        @strongify(self);
        [self.viewModel.requestRemoteDataCommand execute:@1];
    }];
    
    [[MHNotificationCenter rac_addObserverForName:MHReloadFirstPageReloadDataNotification object:nil] subscribeNext:^(NSNotification *note) {
        @strongify(self);
        [self.collectionView reloadData];
    }];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:@"SearhHeaderView"];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.collectionView reloadData];
//    });
    
    
    [[MHNotificationCenter rac_addObserverForName:MHCircleHomeUpdateNotification object:nil] subscribeNext:^(id x) {
        @strongify(self);
        NSMutableDictionary *dic = [[MHIMMessageTransferHelper sharedInstance] fetchChatIMMessageWithName:NSStringFromClass([MHCircleUpdateModel class])];
        if (dic.allKeys.count) {
            [self.navigationItem.rightBarButtonItem showBadgeWithStyle:WBadgeStyleRedDot value:0 animationType:WBadgeAnimTypeNone];
            self.navigationItem.rightBarButtonItem.badgeCenterOffset = kRightItemOffset;
        }else
        {
             [self.navigationItem.rightBarButtonItem clearBadge];
        }
    }];
    
    
    NSMutableDictionary *dic = [[MHIMMessageTransferHelper sharedInstance] fetchChatIMMessageWithName:NSStringFromClass([MHCircleUpdateModel class])];
    if (dic.allKeys.count ) {
        [self.navigationItem.rightBarButtonItem showBadgeWithStyle:WBadgeStyleRedDot value:0 animationType:WBadgeAnimTypeNone];
        self.navigationItem.rightBarButtonItem.badgeCenterOffset = kRightItemOffset;
    }else
    {
        [self.navigationItem.rightBarButtonItem clearBadge];
    }
    [[TIMGroupManager sharedInstance] joinGroup:MH_IM_MIAODONGQUANGROUP msg:@"" succ:^(){
        NSLog(@"Join Succ");
        
    }fail:^(int code, NSString * err) {
        NSLog(@"code=%d, err=%@", code, err);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[[MHHTTPService sharedInstance] getShareWxFriendStatus] subscribeNext:^(MHHTTPResponse *respose) {
            if (![respose isKindOfClass:[NSDictionary class]]) {
                return ;
            }
            [AXAppDelegate sharedDelegate].shareWeChat =  ([[(NSDictionary *)respose objectForKey:@"status"] intValue] == 1);
        }];
    });
    
    

}

- (JKRSearchController *)searchController {
    if (!_searchController) {
        MHSearchCircleResultViewController *resultSearchController = [[MHSearchCircleResultViewController alloc] init];
        resultSearchController.viewModel = [[MHCircleSearchViewModel alloc] initWithServices:self.viewModel.services params:nil];
       
        _searchController = [[JKRSearchController alloc] initWithSearchResultsController:resultSearchController];
        __weak __typeof(self)weakSelf = self;
        resultSearchController.pushBlock = ^{
            weakSelf.searchController.view.hidden = YES;
            
        };
        _searchController.searchBar.placeholder = @"搜索内容或圈子";
        _searchController.hidesNavigationBarDuringPresentation = YES;
        _searchController.searchResultsUpdater = self;
        _searchController.searchBar.delegate = resultSearchController;
//        _searchController.definesPresentationContext = YES;
        _searchController.delegate = self;
    }
    return _searchController;
}

-(void)configurelayout:(CHTCollectionViewWaterfallLayout *)layout
{
    layout.sectionInset = UIEdgeInsetsMake(0, 15, 25, 15);
    layout.headerHeight = 85;
    layout.footerHeight = 5;
    layout.columnCount = 3;
    layout.minimumColumnSpacing = 5;
    layout.minimumInteritemSpacing = 20;
    
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((MH_SCREEN_WIDTH-70)/3, 130);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    UICollectionReusableView *supplementaryView;

    if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]){
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:@"SearhHeaderView" forIndexPath:indexPath];
        self.searchController.searchBar.frame = CGRectMake(15, 20, MH_SCREEN_WIDTH - 30, 35);
        [header addSubview:self.searchController.searchBar];
        supplementaryView = header;
    }else
    {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
        supplementaryView = footerview;
    }
    return supplementaryView;
}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [super collectionView:collectionView didSelectItemAtIndexPath:indexPath];
    
   MHHomeCircleItemCollectionViewCell *cell =  [collectionView cellForItemAtIndexPath:indexPath];
   MHCircleHomeModel *model =   self.viewModel.circles[indexPath.item];
   
    NSMutableDictionary *dic = [[MHIMMessageTransferHelper sharedInstance] fetchChatIMMessageWithName:NSStringFromClass([MHCircleUpdateModel class])];
    [dic removeObjectForKey:[NSString stringWithFormat:@"%d",model.autoId]];
    [[YYCache cacheWithName:MHCacheGlobleKey] setObject:dic forKey:NSStringFromClass([MHCircleUpdateModel class])];
    if (dic.allKeys.count) {
        [self.navigationItem.rightBarButtonItem showBadgeWithStyle:WBadgeStyleRedDot value:0 animationType:WBadgeAnimTypeNone];
        self.navigationItem.rightBarButtonItem.badgeCenterOffset = kRightItemOffset;
    }else
    {
        [self.navigationItem.rightBarButtonItem clearBadge];
    }
//    if (cell.imaConver.lastMessage) {
//        if (cell.imaConver.lastMessage.msg.msgId.length > 0) {
//            model.msgId = cell.imaConver.lastMessage.msg.msgId;
//            [[MHIMMessageTransferHelper sharedInstance] chacheIMMessageWithName:MHChacheIMGroupLastMessage model:model];
//            [[AXAppDelegate sharedDelegate].imGroupImMessageUpdate setObject:model.msgId forKey:model.circleCode];
//        }
//    }else
//    {
//        [cell.imaConver asyncLoadLocalLastMsg:^{
//            if (cell.imaConver.lastMessage.msg.msgId.length > 0) {
//                model.msgId = cell.imaConver.lastMessage.msg.msgId;
//                [[AXAppDelegate sharedDelegate].imGroupImMessageUpdate setObject:model.msgId forKey:model.circleCode];
//            }
//            cell.redDotView.hidden = YES;
//        }];
//        
//        if (cell.imaConver.lastMsg == nil) {
//            cell.redDotView.hidden = YES;
//        }
//    }
  
}


- (UICollectionViewCell *)collectionView:(MHCollectionView *)collectionView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
     return [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(MHHomeCircleItemCollectionViewCell.class) forIndexPath:indexPath];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.searchController.view.hidden) {
         self.searchController.view.hidden = false;
        [self.navigationController setNavigationBarHidden:YES animated:YES];
//        [self.view.window bringSubviewToFront:self.searchController.view];
    }else
    {
        [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        self.navigationController.navigationBar.translucent = NO;
    }
    
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[MHIMMessageTransferHelper sharedInstance] cacheGlobleImGroupUpdate];
   
}

- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(MH_APPLICATION_TOP_BAR_HEIGHT, 0, MH_APPLICATION_TAB_BAR_HEIGHT, 0);
}

- (void)configureCell:(MHHomeCircleItemCollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    [cell bindViewModel:object];
}

- (void)_setupNavigationItem{
    @weakify(self);
//    [RACObserve([MHIMMessageTransferHelper sharedInstance], unReadRecentMessage)
//     subscribeNext:^(NSNumber *x) {
//         @strongify(self);
//         dispatch_async(dispatch_get_main_queue(), ^{
//             if([x integerValue])
//             {
//                 [self.navigationItem.rightBarButtonItem showBadgeWithStyle:WBadgeStyleRedDot value:[x integerValue] animationType:WBadgeAnimTypeNone];
//             }else
//             {
//                  [self.navigationItem.rightBarButtonItem clearBadge];
//             }
//             
//         });
//     }];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem mh_customItemWithTitle:@"动态" titleColor:MHMainTextColor imageName:nil target:self selector:@selector(toTimeLine) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_customItemWithTitle:@"创建" titleColor:MHMainTextColor imageName:nil target:self selector:@selector(createCircle) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_customItemWithTitle:@"创建" titleColor:MHMainTextColor imageName:nil target:self selector:@selector(createCircle) textType:YES];
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_systemItemWithTitle:@"创建" titleColor:MHMainTextColor imageName:nil target:self selector:@selector(createCircle) textType:YES];
//    self.navigationItem.leftBarButtonItem.rac_command = self.viewModel.leftButtonCommand;
}
-(void) createCircle
{
    [self.viewModel.leftButtonCommand execute:nil];
}
-(void) toTimeLine
{
    [[YYCache cacheWithName:MHCacheGlobleKey] removeObjectForKey:NSStringFromClass([MHCircleUpdateModel class])];
//    [MHNotificationCenter postNotificationName:MHCircleHomeUpdateNotification object:nil];
//    [self.collectionView reloadData];
    [self.navigationItem.rightBarButtonItem clearBadge];
    [self.viewModel.rightButtonCommand execute:nil];
}


#pragma mark - JKRSearchControllerDelegate
- (void)willPresentSearchController:(JKRSearchController *)searchController {
//    NSLog(@"willPresentSearchController, %@", searchController);
    self.collectionView.contentInset = UIEdgeInsetsMake(STATUSBAR_HEIGHT - 15 , 0, 0, 0);
    self.collectionView.mj_header.hidden = YES;
    self.view.backgroundColor = RGB(250, 250, 250);
}

- (void)didPresentSearchController:(JKRSearchController *)searchController {
//    NSLog(@"didPresentSearchController, %@", searchController);
}

- (void)willDismissSearchController:(JKRSearchController *)searchController {
//    NSLog(@"willDismissSearchController, %@", searchController);
    dispatch_async(dispatch_get_main_queue(), ^{
        self.collectionView.contentInset = UIEdgeInsetsMake(MH_APPLICATION_TOP_BAR_HEIGHT, 0, MH_APPLICATION_TAB_BAR_HEIGHT, 0);
        //    self.collectionView.mj_header.hidden = NO;
        self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, - MH_APPLICATION_TOP_BAR_HEIGHT);
        MHSearchCircleResultViewController *result = (MHSearchCircleResultViewController *)searchController.searchResultsController;
        self.view.backgroundColor = MHWhiteTextColor;
        result.viewModel.dataSource = @[];
    });
}

- (void)didDismissSearchController:(JKRSearchController *)searchController {
    //    NSLog(@"didDismissSearchController, %@", searchController);
    self.collectionView.mj_header.hidden = NO;
    
}

@end
